import React from 'react';
import { inject, observer } from 'mobx-react';
import {Button,Icon,message,Modal} from 'antd'
import {WeaBrowser, WeaInput,WeaLocaleProvider,WeaCheckbox} from 'ecCom';
import { routerShape } from 'react-router';
import ViewTree from '../../../public/viewtree/ViewTree';
import TaskAdd from '../TaskAdd';
import TaskDetailDialog from '../TaskDetailDialog';
import * as Util from '../../../util/Util';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
@inject('taskDetailStore')
@observer
export default class SubTask extends React.Component {
    static contextTypes = {
        router: routerShape
    }
    constructor(props) {
        super(props);
        this.state = {
            currentAdd:1,
            visible: false,//新建页面控制显隐
            showKey:'',
            parentData:[]
        }
    }
    componentWillMount() {//一些初始化请求
        
    }
    componentDidMount(){
        const{taskDetailStore} = this.props;
        if(taskDetailStore.spinning){
            taskDetailStore.spinning = false;
        }
    }
    //弹出层  新增页面回调成功
    onCallBackSuccess(optparams){
        const { taskDetailStore,sorttype} = this.props;
        const{currentAdd} = this.state;
        let _this = this;
        //taskDetailStore.getSubTaskList({ taskId: detailKey,type:'father'});
        taskDetailStore.setNewTaskInfo(optparams,currentAdd);
        this.setState({visible:false});
        this.addSuccess(optparams,sorttype);
    }
    onEnterSubTask(e,type){//回车键
        let keycode = e.keyCode;
        if(keycode == 13){
         this.addSubTask(type,e.target.value);
        }
    }
    resetUrlKey(){
        //弹框更改url上的_key值
        const { pathname, search,taskDetailStore } = this.props;
        let url = `/${pathname}${search}`;
        if (pathname == undefined || search == undefined) {
            if(location.href.indexOf("/main/workrelate/task/taskDetail")>-1){
                url = "/main/workrelate/task/taskDetail?id="+taskDetailStore.detailKey;
            }else{
                url = "/main/workrelate/task/taskIndex";
            }
        }
        this.context.router.push({
            pathname: url
        });
   }
    /** 添加下级任务 */
    addSubTask(type,val) {
        const { taskDetailStore,sorttype } = this.props;
        const{detailKey} = taskDetailStore;
        if(type==1){
            this.resetUrlKey();
            this.setState({ visible: true, showKey:detailKey,parentData:[{id:detailKey,name:taskDetailStore.editParams.name}],currentAdd:1});
        }else{
            if(val.trim()!="" && val.trim()!="null"){
                let _this = this;
                taskDetailStore.addSubTask({taskName:val,parentid:detailKey,sorttype:sorttype,mainpage:1,relateadd:1,doback:function(optdata){
                    _this.addSuccess(optdata,sorttype,detailKey);
                }}); 
            }
        }
    }
    //新增任务回调
    addSuccess(optparams,sorttype,detailKey){
        if (typeof this.props.doCallBack === "function") {
            if(sorttype==4){
                optparams.opttype = "addchild";
                if(detailKey){
                    optparams.optkey = detailKey;
                }else{
                    optparams.optkey = optparams.parentid;
                }
                this.props.doCallBack("addnew",optparams);
            }else{
                optparams.opttype = "dialogAdd";
                this.props.doCallBack("addnew",optparams);
            }
        }
    }
    onIconClick(key) {//子任务树节点图标点击事件
        const { taskDetailStore } = this.props;
        taskDetailStore.getSubTaskList({ taskId: key });
    }
    //责任选择后回调   taskDetailStore.getSubTaskList({ taskId: detailKey,type:'father'});//刷新子任务
    subBrowser(ids, names, datas,comsbtn,key,otherInfo){
        const { taskDetailStore } = this.props;
        let _this = this;
        if(ids.length>0){
            taskDetailStore.editTaskInfo({
                taskId: key,fieldname: 'principalid',fieldvalue: ids,fieldtype: 'str',issub:1,doback: function () {
                    let arr = {};
                    arr.com = getLabel(84043,'责任人');
                    arr.type = 'principalid';
                    arr.icon = 'edit';
                    arr.title = getLabel(382608,'编辑此任务责任人');
                    comsbtn.map((ele,idx)=>{
                        if(ele.type=='principalid'){ 
                            comsbtn[idx] = arr;
                        }
                        if(comsbtn[idx].custom){
                            comsbtn[idx].custom = '';
                        }
                    });
                    taskDetailStore.optparams = {};
                    let optparamsNew = {}
                    optparamsNew.comsbtn = comsbtn;
                    optparamsNew.opttype = "update";
                    optparamsNew.optkey = key;
                    optparamsNew.rightData = [{name:names,classname:'hrmdiv'}];
                    otherInfo.id = ids;
                    otherInfo.name = names;
                    optparamsNew.otherInfo = otherInfo;
                    taskDetailStore.localtime =  new Date().getTime();
                    taskDetailStore.optparams = optparamsNew;
                    _this.doCallBack("updateperson",names,key);
                }
            });
        }
    }
    //子任务右侧按钮
    onRightBtnClick(key, element, comsbtn,otherInfo,_tags) {
        let type = element.type;
        if (type) {
            const { taskDetailStore } = this.props;
            let  _this = this;
            if (type == "addtask") {//新建任务
                    _this.resetUrlKey();
                    _this.setState({ visible: true,showKey:key,parentData: [{id:key,name:otherInfo.title}],currentAdd:2});
            } else if (type == "principalid") {//责任人
                let arr = {};
                arr.com = (
                    <span
                        onClick={(e) => {
                            e.stopPropagation();
                            e.nativeEvent.stopImmediatePropagation();
                        }}
                        onMouseEnter={e => {
                            this.onRightBtnClick(key, element, comsbtn, otherInfo, _tags)   // 回调onRightBtnClick，防止在责任人浏览按钮输入时无法选中下拉框数据的问题
                        }}
                    >
                        <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@ot6511`} maxBrowerHeight={30} type={1} title={getLabel(84043,'责任人')} replaceDatas={[{id:otherInfo.id,name:otherInfo.name}]}  inputStyle={{ width: 100}}  onChange={(ids, names, datas) => this.subBrowser(ids, names, datas,comsbtn,key,otherInfo)} layout={document.getElementById("treecontent-btns-sub" + key)} />
                    </span>
                )
                arr.type = "principalid";
                comsbtn.map((ele,idx)=>{
                    if(ele.type==type){ 
                        comsbtn[idx] = arr;
                    }
                });
                taskDetailStore.optparams = {};
                let optparamsNew = {}
                optparamsNew.comsbtn = comsbtn;
                optparamsNew.opttype = "update";
                optparamsNew.optkey = key;
                taskDetailStore.optparams = optparamsNew;
            } else if (type == "complete") {//标记完成
                Modal.confirm({
                    title: getLabel(131329,'信息确认'),
                    content: getLabel(508674,'确认要标记此任务为完成吗？'),
                    onOk() {
                        taskDetailStore.toChangeStatus({taskId:key,status:2,comsbtn:comsbtn,type:type,clickType:'child',doback:function(sList){
                            _this.doCallBack('changeStatus',sList,key,2);//数据暂时不回调
                        }});
                    },
                    onCancel() {},
                });
            } else if (type == "progress") {//标记进行
                Modal.confirm({
                    title: getLabel(131329,'信息确认'),
                    content: getLabel(508676,'确认要标记此任务为进行中吗？'),
                    onOk() {
                        taskDetailStore.toChangeStatus({taskId:key,status:1,comsbtn:comsbtn,type:type,clickType:'child',doback:function(sList){
                            _this.doCallBack('changeStatus',sList,key,1);//数据暂时不回调
                        }});
                    },
                    onCancel() {},
                });
            }else if(type == "tag"){//标记标签
                if(_tags){
                    taskDetailStore.checkedIds = _tags.map((d, i) => d.id);
                }
                taskDetailStore.changeSubTagBoxVisible(true,2,key);
            }
        }
    }
    //编辑修改内容回调taskMain.js
    doCallBack(type,dataArray,key,cstatus) {
        if (typeof this.props.doCallBack === "function") {
            this.props.doCallBack(type,dataArray,key,cstatus);
        }
    }
    checkAll(v){
        const { taskDetailStore,taskDetailStore:{editParams,dropSelectedKey}} = this.props;
        let subList = editParams.sublist;
        Util.setDataCheckBoxValue(subList,v,'',4,dropSelectedKey);
        taskDetailStore.editParams.sublist = subList;
        taskDetailStore.allCheckBoxVal = v;
        taskDetailStore.setDropDisplay(Util.isSelectCheckBox(subList,v),true);
    }
    treeOtherClick(key,_v,type,_element){
        const { taskDetailStore } = this.props;
        if(type=='deltag'){
            let _this = this;
            taskDetailStore.editTaskInfo({delvalue:_v,fieldname:"tag",taskId:key,tagtype:"1",doback:function(){
                message.success(getLabel(83472,'删除成功!'), 2);
                _this.doCallBack('tag',_element.tags,key);
            }});
        }else if(type=='checkbox'){
            let isSelect = Util.isSelectCheckBox(taskDetailStore.editParams.sublist,_v);
            let isallselect = Util.isAllSelectCheckBox(taskDetailStore.editParams.sublist,"0");//是否全选
            taskDetailStore.setDropDisplay(isSelect,isallselect);
        }
    }
    render() {
        let { visible,showKey,parentData} = this.state;
        const { taskDetailStore,sorttype} = this.props;
        const { editParams,hasData,cancreate, optparams, localtime,addsubname,onNodeClick,dropSelectedKey,allCheckBoxVal} = taskDetailStore;
        return (
            <div>
                {hasData &&  <div className="subTask">
                                <div className="subTask-list">
                                    {cancreate && <div className="subTask-checkboxall"><WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@bbtub2`} content={getLabel(556,'全选')} value={allCheckBoxVal} onChange={(v)=>this.checkAll(v)}/></div>}
                                    <ViewTree ecId={`${this && this.props && this.props.ecId || ''}_ViewTree@iii5d5`} datas={editParams.sublist} params={toJS(optparams)} onTreeNodeClick={(key) => onNodeClick({key:key})} locationkey={localtime}
                                        onIconClick={(key) => this.onIconClick(key)} onRightBtnClick={(key, element, comsbtn,otherInfo,_tags) => this.onRightBtnClick(key, element, comsbtn,otherInfo,_tags)} 
                                        onOtherClick={(key,_v,_type,_element)=>this.treeOtherClick(key,_v,_type,_element)} boxProp={dropSelectedKey} isSubTree/>
                                </div>
                                {cancreate && <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@trikc6`} className="add-intext" placeholder={getLabel('521216','请输入子任务名称')} value={addsubname} onBlur={val => this.addSubTask(2,val)} onPressEnter={(e)=>this.onEnterSubTask(e,2)}/>}
                                {visible && <TaskAdd ecId={`${this && this.props && this.props.ecId || ''}_TaskAdd@665hau`}  isDialog={true} createvisable={visible}  style={{width: window.innerWidth*0.7, height: window.innerHeight-90}} _minusHeight={90} sorttype={sorttype}
                                    parentData={parentData} onlyClose = {()=>this.setState({ visible: false })}  detailKey={showKey}  onDialogAddSuccess={(arry)=>this.onCallBackSuccess(arry)}/>}
                            </div>
                }
                {!cancreate && editParams.sublist.length==0 && <div className="subTask-nodata">{getLabel(513865,'暂无下级')}</div>}
            </div >
        )
    }
};